<template>
  <div class="register-container">
    <!-- 背景装饰 -->
    <div class="background-decoration">
      <div class="chinese-character">化</div>
      <div class="traditional-building"></div>
      <div class="pattern-overlay"></div>
    </div>

    <!-- 注册表单 -->
    <div class="register-form-container">
      <div class="register-form">
        <h1 class="form-title">用户注册</h1>
        <p class="form-subtitle">加入非物质文化遗产系统</p>
        
        <form @submit.prevent="handleRegister">
          <div class="form-group">
            <div class="input-wrapper">
              <i class="icon user-icon">👤</i>
              <input
                v-model="registerForm.username"
                type="text"
                placeholder="请输入用户名(长度不少于3位)"
                class="form-input"
                :class="{ 'error': errors.username }"
                @blur="validateUsername"
                @input="errors.username = ''"
                required
              />
            </div>
            <div v-if="errors.username" class="error-message">{{ errors.username }}</div>
          </div>

          <div class="form-group">
            <div class="input-wrapper">
              <i class="icon email-icon">📧</i>
              <input
                v-model="registerForm.email"
                type="email"
                placeholder="请输入邮箱"
                class="form-input"
                :class="{ 'error': errors.email }"
                @blur="validateEmail"
                @input="errors.email = ''"
                required
              />
            </div>
            <div v-if="errors.email" class="error-message">{{ errors.email }}</div>
          </div>

          <div class="form-group">
            <div class="input-wrapper">
              <i class="icon phone-icon">📱</i>
              <input
                v-model="registerForm.phone"
                type="tel"
                placeholder="请输入手机号"
                class="form-input"
                :class="{ 'error': errors.phone }"
                @blur="validatePhone"
                @input="errors.phone = ''"
                required
              />
            </div>
            <div v-if="errors.phone" class="error-message">{{ errors.phone }}</div>
          </div>

          <div class="form-group">
            <div class="input-wrapper">
              <i class="icon lock-icon">🔒</i>
              <input
                v-model="registerForm.password"
                type="password"
                placeholder="请输入密码(长度不少于8位)"
                class="form-input"
                :class="{ 'error': errors.password }"
                @blur="validatePassword"
                @input="errors.password = ''"
                required
              />
            </div>
            <div v-if="errors.password" class="error-message">{{ errors.password }}</div>
          </div>

          <div class="form-group">
            <div class="input-wrapper">
              <i class="icon lock-icon">🔒</i>
              <input
                v-model="registerForm.confirmPassword"
                type="password"
                placeholder="请确认密码"
                class="form-input"
                :class="{ 'error': errors.confirmPassword }"
                @blur="validateConfirmPassword"
                @input="errors.confirmPassword = ''"
                required
              />
            </div>
            <div v-if="errors.confirmPassword" class="error-message">{{ errors.confirmPassword }}</div>
          </div>

          <div class="form-group">
            <div class="role-selector">
              <select v-model="registerForm.role" class="role-select">
                <option value="user">普通用户</option>
              </select>
              <i class="icon arrow-icon">⌄</i>
            </div>
          </div>

          <button type="submit" class="register-btn" :disabled="!isFormValid">
            注册
          </button>
        </form>

        <div class="login-link">
          已有账号？<router-link to="/login" class="link">立即登录</router-link>
        </div>
      </div>
    </div>

    <!-- 底部装饰 -->
    <div class="bottom-decoration">
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { register } from '../api/auth'

const router = useRouter()

const registerForm = ref({
  username: '',
  email: '',
  phone: '',
  password: '',
  confirmPassword: '',
  role: 'user'
})

const isLoading = ref(false)
const errors = ref({
  username: '',
  email: '',
  phone: '',
  password: '',
  confirmPassword: ''
})

// 邮箱格式验证
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
// 手机号格式验证（简单验证，以1开头的11位数字）
const phoneRegex = /^1\d{10}$/

// 验证用户名
const validateUsername = () => {
  if (!registerForm.value.username) {
    errors.value.username = '请输入用户名'
  } else if (registerForm.value.username.length < 3) {
    errors.value.username = '用户名长度不少于3位'
  } else {
    errors.value.username = ''
  }
}

// 验证邮箱
const validateEmail = () => {
  if (!registerForm.value.email) {
    errors.value.email = '请输入邮箱'
  } else if (!emailRegex.test(registerForm.value.email)) {
    errors.value.email = '邮箱格式不正确'
  } else {
    errors.value.email = ''
  }
}

// 验证手机号
const validatePhone = () => {
  if (!registerForm.value.phone) {
    errors.value.phone = '请输入手机号'
  } else if (!phoneRegex.test(registerForm.value.phone)) {
    errors.value.phone = '手机号格式不正确'
  } else {
    errors.value.phone = ''
  }
}

// 验证密码
const validatePassword = () => {
  if (!registerForm.value.password) {
    errors.value.password = '请输入密码'
  } else if (registerForm.value.password.length < 8) {
    errors.value.password = '密码长度不少于8位'
  } else {
    errors.value.password = ''
  }
}

// 验证确认密码
const validateConfirmPassword = () => {
  if (!registerForm.value.confirmPassword) {
    errors.value.confirmPassword = '请确认密码'
  } else if (registerForm.value.confirmPassword !== registerForm.value.password) {
    errors.value.confirmPassword = '两次输入的密码不一致'
  } else {
    errors.value.confirmPassword = ''
  }
}

// 提交前验证所有字段
const validateAll = () => {
  validateUsername()
  validateEmail()
  validatePhone()
  validatePassword()
  validateConfirmPassword()
  
  // 检查是否有错误
  return !Object.values(errors.value).some(error => error)
}

const handleRegister = async () => {
  // 先验证所有字段
  if (!validateAll()) {
    ElMessage.warning('请检查表单信息')
    return
  }

  isLoading.value = true
  try {
    const response = await register(registerForm.value)
    if (response.success === true || response.errorCode === 20000){
      ElMessage.success('注册成功，请登录')
      registerForm.value = {
        username: '',
        email: '',
        phone: '',
        password: '',
        confirmPassword: '',
        role: 'user'
      }
      // 清空错误信息
      Object.keys(errors.value).forEach(key => {
        errors.value[key] = ''
      })
      router.push('/login')
    } else {
      ElMessage.error(response.message || '注册失败')
    }
  } catch (error) {
    console.error('注册错误:', error)
    ElMessage.error('注册失败，请检查网络连接')
  } finally {
    isLoading.value = false
  }
}

// 更新按钮的禁用状态
const isFormValid = computed(() => {
  return registerForm.value.username &&
      registerForm.value.email &&
      registerForm.value.phone &&
      registerForm.value.password &&
      registerForm.value.confirmPassword &&
      registerForm.value.password === registerForm.value.confirmPassword &&
      !Object.values(errors.value).some(error => error) &&
      !isLoading.value
})
</script>

<style scoped>
.register-container {
  position: relative;
  width: 100vw;
  height: 100vh;
  background: linear-gradient(135deg, #dc2626 0%, #b91c1c 100%);
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.chinese-character {
  position: absolute;
  top: 10%;
  right: 15%;
  font-size: 180px;
  font-weight: bold;
  color: rgba(139, 28, 28, 0.3);
  font-family: 'SimSun', serif;
  transform: rotate(-10deg);
  user-select: none;
}

.traditional-building {
  position: absolute;
  left: 5%;
  top: 20%;
  width: 280px;
  height: 380px;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 250"><rect x="20" y="150" width="160" height="80" fill="%23667eea" opacity="0.3"/><polygon points="10,150 100,80 190,150" fill="%23667eea" opacity="0.4"/><polygon points="30,130 100,70 170,130" fill="%23667eea" opacity="0.5"/><polygon points="50,110 100,60 150,110" fill="%23667eea" opacity="0.6"/></svg>') no-repeat center;
  background-size: contain;
  opacity: 0.6;
}

.pattern-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: 
    radial-gradient(circle at 20% 20%, rgba(255,255,255,0.1) 1px, transparent 1px),
    radial-gradient(circle at 80% 80%, rgba(255,255,255,0.1) 1px, transparent 1px);
  background-size: 50px 50px;
  opacity: 0.3;
}

.register-form-container {
  position: relative;
  z-index: 2;
  margin-left: auto;
  margin-right: 10%;
}

.register-form {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 40px;
  width: 420px;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.form-title {
  text-align: center;
  color: #333;
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 10px;
  font-family: 'Microsoft YaHei', sans-serif;
}

.form-subtitle {
  text-align: center;
  color: #6b7280;
  font-size: 14px;
  margin-bottom: 30px;
}

.form-group {
  margin-bottom: 18px;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.icon {
  position: absolute;
  left: 15px;
  font-size: 16px;
  z-index: 3;
  pointer-events: none;
}

.form-input {
  width: 100%;
  padding: 13px 13px 13px 45px;
  border: 2px solid #e5e7eb;
  border-radius: 10px;
  font-size: 14px;
  transition: all 0.3s ease;
  background: white;
  box-sizing: border-box;
}

.form-input:focus {
  outline: none;
  border-color: #dc2626;
  box-shadow: 0 0 0 3px rgba(220, 38, 38, 0.1);
}

.form-input.error {
  border-color: #dc2626;
  box-shadow: 0 0 0 3px rgba(220, 38, 38, 0.1);
}

.error-message {
  color: #dc2626;
  font-size: 12px;
  margin-top: 5px;
  margin-left: 5px;
  font-weight: 500;
}

.role-selector {
  position: relative;
  display: flex;
  align-items: center;
}

.role-select {
  width: 100%;
  padding: 13px 45px 13px 13px;
  border: 2px solid #e5e7eb;
  border-radius: 10px;
  font-size: 14px;
  background: white;
  appearance: none;
  cursor: pointer;
  transition: all 0.3s ease;
}

.role-select:focus {
  outline: none;
  border-color: #dc2626;
  box-shadow: 0 0 0 3px rgba(220, 38, 38, 0.1);
}

.arrow-icon {
  position: absolute;
  right: 15px;
  font-size: 14px;
  color: #6b7280;
  pointer-events: none;
}

.register-btn {
  width: 100%;
  padding: 15px;
  background: #dc2626;
  color: white;
  border: none;
  border-radius: 10px;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-top: 10px;
}

.register-btn:hover:not(:disabled) {
  background: #b91c1c;
  transform: translateY(-2px);
  box-shadow: 0 10px 20px rgba(220, 38, 38, 0.3);
}

.register-btn:disabled {
  background: #d1d5db;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.login-link {
  text-align: center;
  margin-top: 20px;
  color: #6b7280;
  font-size: 14px;
}

.link {
  color: #2563eb;
  text-decoration: none;
  font-weight: bold;
}

.link:hover {
  text-decoration: underline;
}

.bottom-decoration {
  position: absolute;
  bottom: 20px;
  right: 20px;
  z-index: 2;
}

.video-icon {
  width: 50px;
  height: 50px;
  background: white;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
  cursor: pointer;
  transition: all 0.3s ease;
}

.video-icon:hover {
  transform: scale(1.1);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.3);
}

@media (max-width: 768px) {
  .register-form-container {
    margin-right: 5%;
  }
  
  .register-form {
    width: 350px;
    padding: 30px;
    max-height: 85vh;
  }
  
  .traditional-building {
    width: 180px;
    height: 280px;
  }
  
  .chinese-character {
    font-size: 100px;
  }
}
</style>
